package com.stx.jeepay.payment.controller.qr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.stx.jeepay.core.enums.CS;
import com.stx.jeepay.core.expection.BizException;
import com.stx.jeepay.core.service.SysConfigService;
import com.stx.jeepay.core.utils.JeepayKit;
import com.stx.jeepay.core.utils.SpringBeansUtil;
import com.stx.jeepay.core.utils.StringKit;
import com.stx.jeepay.payment.channel.IChannelUserService;
import com.stx.jeepay.payment.controller.payorder.AbstractPayOrderController;
import com.stx.jeepay.payment.model.MchAppConfigContext;
import com.stx.jeepay.payment.rqrs.ChannelUserIdRQ;
import com.stx.jeepay.payment.service.ConfigContextQueryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 商户获取渠道用户ID接口
 */
@RestController
@RequestMapping("/api/channelUserId")
public class ChannelUserIdController extends AbstractPayOrderController {
    @Autowired
    private ConfigContextQueryService configContextQueryService;
    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 重定向到微信地址
     **/
    @RequestMapping("/jump")
    public void jump() throws Exception {
        // 获取请求参数
        ChannelUserIdRQ rq = getRQByWithMchSign(ChannelUserIdRQ.class);

        String ifCode = "AUTO".equalsIgnoreCase(rq.getIfCode()) ? getIfCodeByUA() : rq.getIfCode();

        // 获取接口
        IChannelUserService channelUserService =
                SpringBeansUtil.getBean(ifCode + "ChannelUserService", IChannelUserService.class);

        if (channelUserService == null) {
            throw new BizException("不支持的客户端");
        }

        if (!StringKit.isAvailableUrl(rq.getRedirectUrl())) {
            throw new BizException("跳转地址有误");
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mchNo", rq.getMchNo());
        jsonObject.put("appId", rq.getAppId());
        jsonObject.put("extParam", rq.getExtParam());
        jsonObject.put("ifCode", ifCode);
        jsonObject.put("redirectUrl", rq.getRedirectUrl());

        // 回调地址
        String callBackUrl =
                sysConfigService.getDBApplicationConfig().genMchChannelUserIdApiOauth2RedirectUrlEncode(jsonObject);

        // 获取商户配置
        MchAppConfigContext mchAppConfigContext =
                configContextQueryService.queryMchInfoAndAppInfo(rq.getMchNo(), rq.getAppId());
        String redirectUrl = channelUserService.buildUserRedirectUrl(callBackUrl, mchAppConfigContext);
        response.sendRedirect(redirectUrl);
    }

    /**
     * 回调地址
     **/
    @RequestMapping("/oauth2Callback/{aesData}")
    public void oauth2Callback(@PathVariable("aesData") String aesData) throws Exception {
        JSONObject callBackData = JSON.parseObject(JeepayKit.aesDecode(aesData));

        String mchNo = callBackData.getString("mchNo");
        String appId = callBackData.getString("appId");
        String ifCode = callBackData.getString("ifCode");
        String extParam = callBackData.getString("extParam");
        String redirectUrl = callBackData.getString("redirectUrl");

        // 获取接口
        IChannelUserService channelUserService = SpringBeansUtil.getBean(ifCode + "ChannelUserService", IChannelUserService.class);

        if (channelUserService == null) {
            throw new BizException("不支持的客户端");
        }

        // 获取商户配置信息
        MchAppConfigContext mchAppConfigContext =
                configContextQueryService.queryMchInfoAndAppInfo(mchNo, appId);

        //获取渠道用户ID
        String channelUserId = channelUserService.getChannelUserId(getReqParamJSON(), mchAppConfigContext);

        // 同步跳转
        JSONObject appendParams = new JSONObject();
        appendParams.put("appId", appId);
        appendParams.put("channelUserId", channelUserId);
        appendParams.put("extParam", extParam);
        response.sendRedirect(StringKit.appendUrlQuery(redirectUrl, appendParams));
    }

    /**
     * 根据UA获取支付接口
     */
    private String getIfCodeByUA() {
        String ua = request.getHeader("User-Agent");

        // 无法识别扫码客户端
        if (StringUtils.isBlank(ua)) {
            return null;
        }
        if (ua.contains("Alipay")) {
            return CS.IF_CODE.ALIPAY;
        } else if (ua.contains("MicroMessenger")) {
            return CS.IF_CODE.WXPAY;
        }
        return null;
    }
}
